<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- <el-button type="primary" plain size="mini" @click="handleView()">查看log文件</el-button>
        <el-button type="primary" plain size="mini" @click="handleDel()">删除log文件</el-button> -->
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">添加任务</el-button>
        <!-- <el-button type="primary" plain  size="mini" @click="handleRefresh">刷新</el-button> -->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getListFn"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scanList" @selection-change="handleSelectionChange"
      :expand-row-keys="expandKeys" row-key="id">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="expand">
        <template slot-scope="props">
          <div class="detail-container">
            <div class="detail-item" v-for="(file, index) in props.row.logFiles" :key="index">
              <el-button type="text" @click="handleDownloadPdf(file.filePath, file.fileName)">报告下载：{{ file.fileName
                || '' }}</el-button>
              <div class="detail-label">执行进度：</div>
              <div class="detail-content">
                <span v-for="(line, lineIndex) in file.fileContent.split('\n')" :key="lineIndex">
                  {{ line }}
                  <br v-if="lineIndex < file.fileContent.split('\n').length - 1">
                </span>
              </div>
              <div class="detail-actions">
                <el-button size="mini" type="text" @click="handleViewLog(file.filePath)">执行</el-button>
                <el-button size="mini" type="text" @click="handleDeleteLog(file.filePath, props.row)">删除</el-button>
              </div>
            </div>
            <div class="detail-item" v-if="!props.row.logFiles || props.row.logFiles.length === 0">
              <div class="detail-content">暂无日志文件</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="序号" prop="id" width="120" />
      <el-table-column label="任务名称" prop="name" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span class="text-name" style="cursor: pointer" @click="handleNameClick(scope.row)">{{ scope.row.name
            }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="进度" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span class="text-name">{{ scope.row.textName }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="节点名称" prop="port">
        <template slot-scope="scope">
          <span class="text-name" v-if="nodeList.find(item => item.id === scope.row.nodeId)">{{nodeList.find(item =>
            item.id === scope.row.nodeId).name || ''}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-refresh" @click="handleExec(scope.row)">执行</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getListFn" />

    <!-- 添加或修改扫描配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="IP地址" prop="ip">
          <el-input v-model="form.ip" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="节点名称" prop="nodeId">
          <el-select v-model="form.nodeId" placeholder="请选择节点名称">
            <el-option v-for="item in nodeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNode } from "@/api/system/node"
import { getCronPdf } from '@/api/cron'
import { addEvaluate, deleteEvaluate, getEvaluateList, getEvaluateExec, getEvaluateCatLog, getEvaluateRefresh, delEvaluateLog } from '@/api/evaluate'
export default {
  name: "Safe",
  data() {
    return {
      // 展开的行
      expandKeys: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 扫描表格数据
      scanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {
        ip: undefined,
        name: undefined,
        nodeId: undefined,
      },
      // 表单校验
      rules: {
        ip: [
          { required: true, message: "IP地址不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ]
      },
      nodeList: []
    };
  },
  created() {
    this.getListFn();
    this.getNodeList();
  },
  methods: {
    /** 查询扫描列表 */
    getListFn() {
      this.loading = true;
      getEvaluateList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.scanList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        ip: undefined,
        name: undefined,
        nodeId: undefined,
      };
      this.resetForm("form");
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加任务";
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const taskIds = row.taskId || this.ids;
      this.$modal.confirm('是否确认删除任务编号为"' + taskIds + '"的数据项？').then(function () {
        return deleteEvaluate(row.id);
      }).then(() => {
        this.getListFn();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 查看日志文件 */
    handleViewLog(filePath) {
      getEvaluateCatLog({ filePath: filePath }).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("查看log文件成功");
        } else {
          this.$modal.msgError(response.msg || '查看log文件失败');
        }
      });
    },

    /** 删除日志文件 */
    handleDeleteLog(filePath, row) {
      this.$modal.confirm('是否确认删除该日志文件？').then(() => {
        return delEvaluateLog({ filePath: filePath });
      }).then(response => {
        this.$modal.msgSuccess("删除成功");
        // 只刷新当前行的日志文件列表
        getEvaluateRefresh({ id: row.id }).then(response => {
          if (response.code === 200) {
            this.$set(row, 'logFiles', response.data);
          }
        });
      }).catch(() => { });
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.taskId != undefined) {
            updateEvaluate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getListFn();
            });
          } else {
            addEvaluate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getListFn();
            });
          }
        }
      });
    },
    /** 查看按钮操作 */
    handleView() {
      getEvaluateCatLog().then(response => {
        this.$modal.msgSuccess("查看log文件");
      });
    },
    /** 执行按钮操作 */
    handleExec(row) {
      getEvaluateExec({ id: row.id }).then(response => {
        this.$modal.msgSuccess("执行成功");
      });
    },
    // 获取节点列表
    getNodeList() {
      listNode({
        pageNum: 1,
        pageSize: 1000,
      }).then(response => {
        this.nodeList = response.rows || [];
      }).catch(error => {
        this.$message.error('获取节点列表失败：' + error.message);
      });
    },
    handleRefresh() {
      getEvaluateRefresh().then(response => {
        this.$modal.msgSuccess("刷新成功");
        this.getListFn();
      });
    },
    handleDel() {
      delEvaluateLog().then(response => {
        this.$modal.msgSuccess("删除成功");
        this.getListFn();
      });
    },
    handleNameClick(row) {
      getEvaluateRefresh({ id: row.id }).then(response => {
        if (response.code === 200) {
          // 设置日志文件数据到当前行
          this.$set(row, 'logFiles', response.data);
          // 展开当前行
          if (!this.expandKeys.includes(row.id)) {
            this.expandKeys.push(row.id);
          }
        } else {
          this.$modal.msgError(response.msg || '获取日志文件失败');
        }
      });
    },
    /** 下载PDF文件 */
    handleDownloadPdf(filePath, taskName) {
      getCronPdf({ resource: filePath }).then(response => {
        // 创建一个Blob对象
        const blob = new Blob([response], { type: 'application/pdf' });
        // 创建一个临时的URL
        const url = window.URL.createObjectURL(blob);
        // 创建一个临时的a标签
        const link = document.createElement('a');
        link.href = url;
        // 使用任务名称作为文件名，如果没有则使用默认名称
        const fileName = (taskName || 'report');
        link.setAttribute('download', fileName);
        // 添加到body
        document.body.appendChild(link);
        // 触发点击
        link.click();
        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        this.$modal.msgSuccess("PDF下载成功");
      }).catch(error => {
        this.$modal.msgError('PDF下载失败：' + error.message);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.detail-container {
  padding: 20px;
  background: #f8f8f8;
  border-radius: 4px;
  margin: 10px 20px;

  .detail-item {
    margin-bottom: 15px;

    &:last-child {
      margin-bottom: 0;
    }

    .detail-label {
      font-weight: bold;
      color: #606266;
      margin-bottom: 5px;
    }

    .detail-content {
      color: #333;
      line-height: 1.5;
      word-break: break-all;
      white-space: pre-wrap;
    }

    .detail-actions {
      margin-top: 8px;

      .el-button {
        padding: 4px 8px;
        margin-right: 8px;

        &:last-child {
          margin-right: 0;
        }
      }
    }
  }
}

.text-name {
  color: #409EFF !important; // Element UI's primary blue color
}
</style>